//index.js
//获取应用实例

var sourceType = [
  ['camera'],
  ['album'],
  ['camera', 'album']
]
var sizeType = [
  ['compressed'],
  ['original'],
  ['compressed', 'original']
]
var app = getApp();
var util = require('../../utils/util.js');
var applet_park_api_url = app.globalData.applet_park_api_url;
var applet_park_api_url_imgUrl = app.globalData.applet_park_api_url_imgUrl;
Page({
  data: {
    imgUrl: applet_park_api_url_imgUrl,
    restaurantId: '',
    imageList: [],
    pics: [],
    workid: '',
    comremark: '',
    currenttext: 10,
    starClassNum: 5,
    starDesc: '非常满意，无可挑剔',
    orderNo: '',
    stars: [{
      lightImg: applet_park_api_url_imgUrl + '/star_light.png',
      blackImg: applet_park_api_url_imgUrl + '/star_black.png',
      flag: 1,
      message: '非常不满意，各方面都很差'
    }, {
      lightImg: applet_park_api_url_imgUrl + '/star_light.png',
      blackImg: applet_park_api_url_imgUrl + '/star_black.png',
      flag: 1,
      message: '不满意，比较差'
    }, {
      lightImg: applet_park_api_url_imgUrl + '/star_light.png',
      blackImg: applet_park_api_url_imgUrl + '/star_black.png',
      flag: 1,
      message: '一般，还要改善'
    }, {
      lightImg: applet_park_api_url_imgUrl + '/star_light.png',
      blackImg: applet_park_api_url_imgUrl + '/star_black.png',
      flag: 1,
      message: '比较满意，仍要改善'
    }, {
      lightImg: applet_park_api_url_imgUrl + '/star_light.png',
      blackImg: applet_park_api_url_imgUrl + '/star_black.png',
      flag: 1,
      message: '非常满意，无可挑剔'
    }],
    assessLists: ['不错', '节约时间', '很干净', '很可口', '实惠分量足', '价格公道'],
    sources: ''
  },

  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (options) {
    var that = this;
    if (options.restaurantId) {
      that.setData({
        restaurantId: options.restaurantId
      })
    }
    if (options.orderNo) {
      that.setData({
        orderNo: options.orderNo
      })
    }

  },
  starClick: function (e) {
    var that = this;
    for (var i = 0; i < that.data.stars.length; i++) {
      var allItem = 'stars[' + i + '].flag';
      that.setData({
        [allItem]: 2
      })
    }
    var index = e.currentTarget.dataset.index;
    for (var i = 0; i <= index; i++) {
      var item = 'stars[' + i + '].flag';
      that.setData({
        [item]: 1
      })
    }
    // 评价星星文字说明
    let starClassNum = index + 1;
    this.setData({
      starDesc: this.data.stars[index].message,
      starClassNum: starClassNum
    })
  },
  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  chooseImage_album: function (e) { //选择图片

    var that = this;
    wx.chooseImage({
      sourceType: sourceType[2],
      count: 9,
      success: function (res) {
        var imgsrc = res.tempFiles;
        var pics = that.data.pics.concat(imgsrc);
        var imageList = that.data.imageList.concat(imgsrc);
        // for (var obj of res.tempFiles) {
        //   obj.showOrder = that.data.showOrder;
        //   that.data.showOrder++;
        // }
        that.setData({
          pics: pics,
          imageList: imageList
        })
      }
    })
  },
  handleImagePreview(e) {
    const idx = e.target.dataset.idx
    var src = e.currentTarget.dataset.src;
    const images = this.data.imagepreList;

    wx.previewImage({
      current: src, //当前预览的图片
      urls: images, //所有要预览的图片
    })
  },
  delect(e) { //删除图片

    var pics = this.data.pics;
    var imageList = this.data.imageList;
    // var imagepreList = this.data.imagepreList;
    var index = e.currentTarget.dataset.idx;
    pics.splice(index, 1);
    imageList.splice(index, 1);
    // imagepreList.splice(index, 1);
    this.setData({
      pics: pics,
      imageList: imageList

    });
  },
  submit: function () { //提交评价
    var that = this;
    var source = '';
    var finished = true;
    for (var pic of that.data.imageList) {
      if (!pic.picUrl) { //false
        finished = false;
        break;
      }
    }

    if (finished) {
      wx.hideLoading();

      // wx.navigateBack();
      that.submitEEvaluations();
      return;
    }

    //用自执行函数,来解决循环内部的异步回调问题
    (function uploadImage(i) { //上传图片
      if (i >= that.data.imageList.length) {
        return;
      }

      // var image = that.data.imageList[i];
      if (!that.data.imageList[i].picUrl && that.data.imageList[i].path) {
        var path = that.data.imageList[i].path;
        wx.uploadFile({
          url: 'https://jinchengit.cn:9999/api/upload',
          filePath: path,
          name: 'files',
          success(res) {
            let response = JSON.parse(res.data);
            that.data.imageList[i].picUrl = "https://zjurainforest.com:9999" + response.data[0];
            source = that.data.sources + response.data + ",";
            that.data.sources = source;
            that.setData(that.data);
            //检测下其他图片有没有传完
            var allFinished = true;
            for (var pic of that.data.imageList) {
              if (!pic.picUrl) { //false
                allFinished = false;
                break;
              }
            }
            if (allFinished) { //全部传完了,则隐藏加载按钮并返回
              wx.hideLoading();
              //数据回传录车页面,返回
              that.submitEEvaluations();
              //wx.navigateBack();
            } else {
              uploadImage(i + 1);
            }
          },
          fail(res) {
            
          }
        })
      } else {
        uploadImage(i + 1);
      }
    })(0);
  },
  seclectDes(e) {
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    this.setData({
      currenttext: index,
      comremark: item
    })
  },
  bindKeyInput: function (e) {
    this.data[e.currentTarget.dataset.inputname] = e.detail.value;
    this.setData(this.data);
  },

  submitEEvaluations() {
    var that = this;
    if (that.data.starClassNum <= 4) {
      if (!that.data.comremark) {
        wx.showToast({
          title: '请填写备注说明',
        })
        return

      }
    }
    var id = app.globalData.id || wx.getStorageSync("id");
    wx.request({
      url: applet_park_api_url + '/api/restaurantEvaluations',
      data: {
        restaurantId: that.data.restaurantId,
        sysUserId: id,
        content: that.data.comremark,
        images: that.data.sources,
        starClassNum: that.data.starClassNum,
        orderNo: that.data.orderNo,
        stauts: '3'
      },
      method: 'POST',
      success: function (res) {
        if (res.data.code == 0) {

          wx.showToast({
            title: '评价成功',
          })
          var pages = getCurrentPages();

          var prevPage = pages[pages.length - 2]; //上一个页面
          var prevPage1 = pages[pages.length - 3]; //上一个页面
          prevPage.getData();
          prevPage1.getData();
          prevPage.setData({
            reLoad: true, //控制前一个页面刷新　　　
          })
          prevPage1.setData({
            reLoad: true, //控制前一个页面刷新　　　
          })
          wx.navigateBack({
            delta: 1
          })
        } else {
          wx.showToast({
            title: '评价失败',
          })
        }
      },
      fail: function (e) {
        util.showError("设置失败".e)
      }
    })


    // requestDataparams('/api/restaurantEvaluations', {
    //   restaurantId: that.data.restaurantId,
    //   sysUserId: id,
    //   content: that.data.comremark,
    //   images: that.data.sources,
    //   starClassNum: that.data.starClassNum
    // }, 'POST').then(res => {
    //   if (res.data.code == 0) {

    //     wx.showToast({
    //       title: '评价成功',
    //     })
    //     var pages = getCurrentPages();

    //     var prevPage = pages[pages.length - 2]; //上一个页面
    //     wx.navigateBack();
    //   } else {
    //     wx.showToast({
    //       title: '评价失败',
    //     })
    //   }
    // }).catch(err => {
    //   
    // });

  },
})